package cn.rulian.base.basis.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.rulian.base.basis.bo.SortManager;
import cn.rulian.base.basis.dao.SortManagerDao;
import cn.rulian.base.basis.vo.SortManagerVo;
import cn.rulian.base.common.service.BaseService;
import cn.rulian.base.common.util.xx;
import cn.rulian.base.common.vo.Result;

/**
 * 分类管理器Service
 */
@Service
@Transactional(readOnly = true)
public class SortManagerService extends BaseService<SortManager>
{

	// private final Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	EntityManager em;

	@Autowired
	private SortManagerDao dao;

	@Override
	protected SortManagerDao getDao()
	{
		return dao;
	}
		
	/**
	 * 查询
	 */
	public Result query(final SortManagerVo vo)
	{
		Sort sort = new Sort("desc".equals(vo.getOrder())?Direction.DESC:Direction.ASC, vo.getSort()); // 排序
		Pageable pageable = new PageRequest(vo.getPage() - 1, vo.getRows(), sort); // 分页查询条件

		//动态查询对象
		Specification<SortManager> specification = new Specification<SortManager>()
		{
			@Override
			public Predicate toPredicate(Root<SortManager> root, CriteriaQuery<?> cq, CriteriaBuilder cb)
			{
				return buildPredicate(root, cb, vo);
			}
		};

		// 查询
		Page<SortManager> page = dao.findAll(specification, pageable);
		Result result = Result.getResult(page);


		return result;
	}
	

	/**
	 * 构建查询条件
	 */
	private Predicate buildPredicate(Root<SortManager> root, CriteriaBuilder cb, SortManagerVo vo)
	{
		List<Predicate> predicates = new ArrayList<Predicate>();


		//key
		String key = vo.getKey();
		if(!xx.isEmpty(key))
		{
			predicates.add(cb.like(root.<String> get("key"), "%" + key + "%"));
		}


		//分类名称
		String name = vo.getName();
		if(!xx.isEmpty(name))
		{
			predicates.add(cb.like(root.<String> get("name"), "%" + name + "%"));
		}


		return cb.and(predicates.toArray(new Predicate[predicates.size()]));
	}

	/**
	 * 根据key，查询SortManager
	 */
	public SortManager findFirstByKey(String key)
	{
		return dao.findFirstByKey(key);
	}


}
